package pl.edu.pw.ee.buildcity.scm.subversion;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.tmatesoft.svn.core.wc.SVNRevision;
import pl.edu.pw.ee.buildcity.commons.exceptions.BuildCityRuntimeException;
import pl.edu.pw.ee.buildcity.scm.SCMConnector;

import java.net.URI;
import java.net.URISyntaxException;

import static org.apache.commons.lang.StringUtils.isBlank;

/**
 * @author mgrzechocinski
 * @since 2009-10-10
 */
public class SVNCheckoutParameters {

	private static final Logger log = Logger.getLogger(SVNCheckoutParameters.class);

	public final SCMConnector connector;
	public final String host;
	public final Integer port;
	public final String pathToCheckout;
	public final SVNRevision revisionToCheckout;

	private static final int UNDEFINED_PORT = -1;

	public static SVNCheckoutParameters checkoutHEAD(String url) {
		return checkout(url, SVNRevision.HEAD);
	}

	public static SVNCheckoutParameters checkoutRevision(String url, SVNRevision revision) {
		return checkout(url, revision);
	}

	private static SVNCheckoutParameters checkout(String url, SVNRevision revision) {
		try {
			URI urlToCheckout = new URI(url);

			final SCMConnector scmConnector = SCMConnector.getByProtocol(urlToCheckout.getScheme());
			final String host = urlToCheckout.getHost();
			//If no port specified - use connector default port
			final int port = urlToCheckout.getPort() != UNDEFINED_PORT ? urlToCheckout.getPort() : scmConnector.getPort();
			final String path = urlToCheckout.getPath();

			if (scmConnector == null || isBlank(host) || isBlank(path) || port == UNDEFINED_PORT) {
				throw new URISyntaxException(url, "URL is malformed");
			}

			return new SVNCheckoutParameters(revision, scmConnector, host, port, path);

		} catch (URISyntaxException e) {
			throw new BuildCityRuntimeException("Malformed url to checkout: " + url, e);
		}
	}

	private SVNCheckoutParameters(SVNRevision revisionToCheckout, SCMConnector connector, String host, Integer port, String pathToCheckout) {
		this.connector = connector;
		this.host = host;
		this.port = port;
		this.pathToCheckout = pathToCheckout;
		this.revisionToCheckout = revisionToCheckout;
		//log.info("Created SVNCheckoutParameters: " + this);
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
	}
}